package com.bootdo.jiashan.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.config.Constant;
import com.bootdo.common.domain.Tree;
import com.bootdo.common.utils.*;
import com.bootdo.jiashan.domain.StandardAreaDO;
import com.bootdo.jiashan.model.Area;
import com.bootdo.jiashan.model.SupplierModel;
import com.bootdo.jiashan.model.SupplyProductModel;
import com.bootdo.jiashan.service.StandardAreaService;
import com.bootdo.jiashan.service.SupplierService;
import com.bootdo.system.domain.MenuDO;
import com.bootdo.system.domain.RoleDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bootdo.jiashan.domain.SupplyProductDO;
import com.bootdo.jiashan.service.SupplyProductService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 
 * @author hejinen
 * @email 1992lcg@163.com
 * @date 2019-05-14 23:39:41
 */
 
@Controller
@RequestMapping("/jiashan/supplyProduct")
@Slf4j
public class SupplyProductController {
	@Autowired
	private SupplyProductService supplyProductService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private StandardAreaService standardAreaService;
	
	@GetMapping()
	@RequiresPermissions("jiashan:supplyProduct:supplyProduct")
	String SupplyProduct(){
	    return "jiashan/supplyProduct/supplyProduct";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jiashan:supplyProduct:supplyProduct")
	public PageUtils list(@RequestParam Map<String, Object> params,boolean export){
		//查询列表数据
        if((params.get("standard").toString().equals("0"))){
			System.out.println("1");
			if(params.get("area") != null && StringUtils.isNotEmpty((String)params.get("area"))){
				System.out.println("2");
				Map<String, Object> areaParams = new HashMap<>();
				areaParams.put("area",params.get("area"));
				List<StandardAreaDO> list = standardAreaService.list(areaParams);
				if(CollectionUtils.isNotEmpty(list)){
					params.put("standard",list.get(0).getStandard());
				}
			}else{
				params.remove("standard");
			}
		}
        if(StringUtils.isNotBlank((String)params.get("weightStr"))){
			params.put("weight", MoneyConvert.DollarToCentForLong((String)params.get("weightStr")));
		}

		Query query = new Query(params);
		List<SupplyProductModel> supplyProductList = supplyProductService.list(query);
		int total = supplyProductService.count(query);
		PageUtils pageUtils = new PageUtils(supplyProductList, total);
		return pageUtils;
	}

	@ResponseBody
	@PostMapping("/exportExcel")
	@RequiresPermissions("jiashan:supplyProduct:supplyProduct")
	public String exportExcel(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response){
		if((params.get("standard").toString().equals("0"))){
			System.out.println("1");
			if(params.get("area") != null && StringUtils.isNotEmpty((String)params.get("area"))){
				System.out.println("2");
				Map<String, Object> areaParams = new HashMap<>();
				areaParams.put("area",params.get("area"));
				List<StandardAreaDO> list = standardAreaService.list(areaParams);
				if(CollectionUtils.isNotEmpty(list)){
					params.put("standard",list.get(0).getStandard());
				}
			}else{
				params.remove("standard");
			}
		}
		if(StringUtils.isNotBlank((String)params.get("weightStr"))){
			params.put("weight", MoneyConvert.DollarToCentForLong((String)params.get("weightStr")));
		}
		Date date =new Date();
		SimpleDateFormat sdf =new SimpleDateFormat("yyyyMMddHHmmss");
		String time =sdf.format(date);
		response.setHeader("Content-Disposition", "attachment;filename=File" + time +".xlsx");
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		XSSFWorkbook workbook = supplyProductService.exportExcel(params);
		try(OutputStream output= response.getOutputStream();
			BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);) {
			bufferedOutPut.flush();
			workbook.write(bufferedOutPut);
		} catch (Exception e) {
			log.error("exportExcel exception",e);
		}
		return null;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jiashan:supplyProduct:add")
	String add(Model model){
		List<SupplierModel> supplierModels = supplierService.list(null);
		model.addAttribute("supplierModels", supplierModels);
	    return "jiashan/supplyProduct/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jiashan:supplyProduct:edit")
	String edit(@PathVariable("id") Integer id,Model model){
		SupplyProductDO supplyProduct = supplyProductService.get(id);
		model.addAttribute("supplyProduct", supplyProduct);
		List<SupplierModel> supplierModels = supplierService.list(null);
		model.addAttribute("supplierModels", supplierModels);
	    return "jiashan/supplyProduct/edit";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jiashan:supplyProduct:add")
	public R save( SupplyProductDO supplyProduct) throws IllegalAccessException {
		if(supplyProductService.save(supplyProduct)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jiashan:supplyProduct:edit")
	public R update( SupplyProductDO supplyProduct){
		supplyProductService.update(supplyProduct);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jiashan:supplyProduct:remove")
	public R remove( Integer id){
		if(supplyProductService.remove(id)>0){
			return R.ok();
		}
		return R.error();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jiashan:supplyProduct:batchRemove")
	public R remove(@RequestParam("ids[]") Integer[] ids){
		supplyProductService.batchRemove(ids);
		return R.ok();
	}

	@GetMapping("/areaTree/{standard}")
	String areaTree(@PathVariable("standard") Integer standard,Model model){
		model.addAttribute("standard", standard);
		return "jiashan/supplyProduct/areaTree";
	}

	@GetMapping("/getAreaTreeData/{standard}")
	@ResponseBody
	Tree<Area> tree(@PathVariable("standard") Integer standard) {
		Tree<Area> tree = standardAreaService.getTree(standard);
		return tree;
	}

	@PostMapping("/areaTreeUpdate/{standard}")
	@ResponseBody()
	R update(@PathVariable("standard") Integer standard,String[] areaIds) {
		standardAreaService.updateByStandard(standard,areaIds);
		return R.ok();
	}


}
